<template>
  <el-card class="main-container">
    <template #header>
      <div class="card-header">
        <span>位置列表</span>
      </div>
    </template>
    
    <!-- 查询条件区域 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input 
            v-model="form.targetId" 
            placeholder="Target ID" 
            clearable 
          />
        </el-col>
        <el-col :span="7">
          <el-input 
            v-model="form.routeId" 
            placeholder="Route ID" 
            clearable 
          />
        </el-col>
        <el-col :span="5">
          <el-button 
            type="primary" 
            @click="handleClick"
          >
            刷新
          </el-button>
        </el-col>
        <el-col :span="5">
          <el-button 
            type="danger" 
            @click="handleDeleteAll"
          >
            清除所有 locations
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <el-table 
      :data="tableData" 
      style="width: 100%" 
      border 
      stripe
      size="default"
    >
      <el-table-column prop="locationId" label="ID" align="center" width="220" />
      <el-table-column prop="targetId" label="Target ID" align="center" width="220" />
      <el-table-column prop="routeId" label="Route ID" align="center" width="220" />
      <el-table-column prop="lng" label="经度" align="center" />
      <el-table-column prop="lat" label="纬度" align="center" />
      <el-table-column prop="speed" label="速度" align="center" />
      <el-table-column label="时间" align="center" width="180">
        <template #default="{ row }">
          {{ formatDate(row.date) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-row :gutter="20" align="middle">
        <el-col :span="4">
          <div class="info-item">
            <span>总条数：</span>
            <el-tag>{{ form.totalElements }}</el-tag>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="info-item">
            <span>总页数：</span>
            <el-tag>{{ form.totalPages }}</el-tag>
          </div>
        </el-col>
        <el-col :span="10">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="form.size"
            :page-sizes="[5, 10, 20, 50]"
            :total="form.totalElements"
            layout="sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-col>
        <el-col :span="6">
          <div class="jump-page">
            <el-input
              v-model="jumpPage"
              placeholder="页码"
              style="width: 100px"
              @keyup.enter="handleJumpPage"
            >
              <template #append>
                <el-button @click="handleJumpPage">
                  跳转
                </el-button>
              </template>
            </el-input>
          </div>
        </el-col>
      </el-row>
    </div>
  </el-card>
</template>

<script>
import { onActivated, onMounted, reactive, ref } from "vue"
import api from "../api/api"
import AxiosInstance from "../utils/axios-instance"
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: "location-page",
  setup() {
    const form = reactive({
      totalElements: 0,
      totalPages: 0,
      size: 20,
      page: 0,
      targetId: '',
      routeId: ''
    })

    const currentPage = ref(1)
    const tableData = ref([])
    const jumpPage = ref('')

    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }

    async function handleClick() {
      try {
        const response = await api.getLocations(
          form.targetId,
          form.routeId,
          form.page,
          form.size
        )
        console.log('API Response:', response);
        
        if (response && response.content) {
          tableData.value = response.content
          form.totalElements = response.totalElements
          form.totalPages = response.totalPages
          console.log('Loaded data:', tableData.value);
        } else {
          console.warn('No data in response:', response);
          tableData.value = []
          form.totalElements = 0
          form.totalPages = 0
          currentPage.value = 1
        }
      } catch (error) {
        console.error('API Error:', error)
        ElMessage.error('取数据失败: ' + (error.message || '未知错误'))
        tableData.value = []
        form.totalElements = 0
        form.totalPages = 0
        currentPage.value = 1
      }
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        AxiosInstance.delete("/locations/" + row.locationId).then(() => {
          api.getLocations(form.targetId, form.routeId, form.page, form.size).then(response => {
            form.totalElements = response.totalElements
            form.totalPages = response.totalPages
            tableData.value = response.content
            ElMessage.success('删除成功')
          })
        }).catch(error => {
          console.error('Delete failed:', error)
          ElMessage.error('删除失败: ' + (error.message || '未知错误'))
        })
      }).catch(() => {
        // 取消删除时不做任何操作
      })
    }

    const handleSizeChange = (val) => {
      form.size = val
      currentPage.value = 1
      form.page = 0
      handleClick()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      form.page = val - 1
      handleClick()
    }

    const handleJumpPage = () => {
      const page = parseInt(jumpPage.value)
      if (isNaN(page) || page < 1 || page > form.totalPages) {
        ElMessage.warning(`请输入1-${form.totalPages}之间的页码`)
        return
      }
      currentPage.value = page
      form.page = page - 1
      handleClick()
      jumpPage.value = ''
    }

    const handleDeleteAll = () => {
      ElMessageBox.confirm('确定要清除所有记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteLocationsAll().then(() => {
          ElMessage.success('清除完成')
          handleClick() // 刷新数据
        }).catch(error => {
          console.error('Delete all failed:', error)
          ElMessage.error('清除失败: ' + (error.message || '未知错误'))
        })
      }).catch(() => {
        // 取消删除时不做任何操作
      })
    }

    onActivated(() => {
      handleClick()
    })

    return {
      form,
      tableData,
      currentPage,
      handleClick,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      jumpPage,
      handleJumpPage,
      formatDate,
      handleDeleteAll
    }
  }
}
</script>

<style scoped>
.main-container {
  margin: 20px;
}

.card-header {
  font-weight: bold;
}

.filter-section {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.jump-page {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  background-color: #f5f7fa;
}

:deep(.el-table .cell) {
  padding: 8px;
}

.el-input {
  width: 100%;
}

.el-button {
  width: 100%;
}
</style>